package com.asm.blog.shiro;

import cn.hutool.json.JSONUtil;
import com.asm.blog.common.lang.Result;
import com.asm.blog.util.JwtUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 定义 jwt的过滤器 JwtFilter  交给 ShiroConfig配置文件使用
 *
 * 可以继承两种
 *
 * 1.    AuthenticatingFilter    ：实现了基本的自动登录逻辑
 *
 * 2.    BasicHttpAuthenticationFilter    ：可以自动在请求头辨别token信息 进行封装
 */
@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    JwtUtils jwtUtils;

    /**
     * ------------------------------------------------------------
     *                                                            /
     *       功能： 创建 令牌           【 最先执行3 】               /
     *       调用： shiro的 executeLogin()执行登录 会调用            /
     *                                                            /
     * ============================================================
     *
     *  前后端分离，要求用户登录成功拿到jwt后，请求要放入 header里面访问，所以方法内 从 header 里取数据
     * @param servletRequest
     * @param servletResponse
     * @return
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 从头部获取 jwt
        String jwt = request.getHeader("Authorization");

        // 没有 返回空； 有则 处理返回对象
        if(StringUtils.isEmpty(jwt))
        {
            return null;
        }

        return new JwtToken(jwt);
    }

    /**
     * 访问有要求登录的资源时 处理                    【 最先执行2 ，】
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 从头部获取 jwt
        String jwt = request.getHeader("Authorization");

        // 没有 返回  true 交给 控制器注解 拦截
        if(StringUtils.isEmpty(jwt))
        {
            return true;
        }else{

            // 校验 jwt
            Claims cliam = jwtUtils.getClaimByToken(jwt);

            if(cliam == null || jwtUtils.isTokenExpired(cliam.getExpiration()))throw new ExpiredCredentialsException("token已失效,请重新登录");

            /**
             * 执行登录
             *
             * 这里登陆失败将进入  this.onLoginFailure()方法处理 【所以要重写】
             */
            return executeLogin(servletRequest, servletResponse);
        }

    }

    /**
     * 登录 失败时 处理 【 登录失败将调用 , 譬如 锁定账号了】
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        // 强转
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        // 获取登录失败信息
        Throwable throwable = e.getCause() == null ? e : e.getCause();

        // 登录失败信息 统一处理结果类
        String msg = throwable.getMessage();
        Result result = Result.fail(msg);

        // 转换为 json , 同时 过滤 null 值
        String json = JSONUtil.toJsonStr(result);

        // 前端显示出去
        try {
            servletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
            servletResponse.getWriter().print(json);

        } catch (IOException ioException) {

        }


        return false;
    }

    /**
     * 前置方法                             【 最先执行1 】
     *  跨域问题解决
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }
}
